/*
 * Copyright (c) 2018.
 * 北京九思金信科技有限公司对该文件内容保留所有权利。
 * 未经许可，不得私自拷贝、传播、发布、引用该文件内容，违者将被追究法律责任。
 */

import Vue from 'vue'
import Vuex from 'vuex'
import {instance as http} from '../utils/http'

Vue.use(Vuex)
const findMenuItem = (menuItems, appletId, path) => {
  if (!menuItems) {
    return null
  }
  const item = menuItems.find(item => {
    if (item.appletId == appletId) {
      path = path.concat(item.appletName)
      return true
    }
    const tmp = findMenuItem(item.children, appletId, path.concat(item.menuItemName))
    if (tmp) {
      path = tmp
      return true
    } else {
      return false
    }
  })
  if (item) {
    return path
  } else {
    return null
  }
}
const store = new Vuex.Store({
  state: {
    menu: [],
    activeIndex: -1,
    applets: [],
    displayApplets: [],
    paths: [],
    routers: {},
    user: {},
    tenant: {},
    openAppletName:null
  },
  mutations: { //通过commit来触发mutation
    ['SET_MENU'](state, menuItems) {
      state.menu = menuItems;
    },
    ['SET_USER'](state, userData) {
      state.user = userData
    },
    ['SET_TENANT'](state, tenantData) {
      state.tenant = tenantData
    },
    ['OPEN_APPLET'](state, applet) {
      state.openAppletName = applet.appletName
      state.applets.push(applet)
      state.activeIndex = state.applets.length - 1
      applet.idx = state.applets.length - 1
      state.displayApplets.push(applet)
    },
    ['CLOSE_APPLET'](state, idx) {
      state.applets.splice(idx, 1)
      if (idx <= state.activeIndex) {
        state.activeIndex--
      }
    },
    ['CLOSE_DISPLAY_APPLET'](state) {
      state.displayApplets = []
    },
    ['ACTIVE_APPLET'](state, idx) {
      state.activeIndex = idx
    },
    ['ADD_PATH'](state, path) {
      state.paths.push(path)
    },
    ['DEL_PATH'](state, idx) {
      state.paths.splice(idx, 1)
    },
    ['RELOAD_APPLET'](state, applet) {
      state.applets.splice(state.activeIndex, 1, applet)
    },
  },
  actions: {
    /**
     * 加载菜单
     * @param commit
     */
    loadMenu({commit}) {
      const url = '/joys-rest/joys-master-data/admin/menuItems/permitted'
      http.get(url).then(res => {
        commit('SET_MENU', res.data)
      })
    },
    /**
     * 加载当前用户
     * @param commit
     */
    loadUser({commit}) {
      http.get('/joys-rest/joys-master-data/users/self').then(res => {
        commit('SET_USER', res.data)
      })
    },
    /**
     * 加载当前租户
     */
    loadTenant({commit}) {
      http.get('/joys-rest/joys-master-data/tenant/self').then(resp => {
        commit('SET_TENANT', resp.data)
      })
    },
    /**
     * 激活应用
     * @param commit
     * @param idx
     */
    activeApplet({commit}, idx) {
      commit('ACTIVE_APPLET', idx)
    },
    /**
     * 打开应用
     * @param state
     * @param commit
     * @param appletId
     */
    openApplet({state, commit, dispatch}, params) {
      if (!params || !params.appletId) {
        return
      }
      const appletId = params.appletId
      //params to uri query str
      let query = ''
      for (let key in params) {
        let value = params[key]
        if (value.constructor === Array || value.constructor === Object) {
          value = JSON.stringify(value)
        } else {
          value = value + ''
        }
        query += encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&'
      }
      query = query.substr(0, query.length - 1)

      let applet = state.applets.find((applet, idx) => {
        if (applet.appletId == appletId) {
          state.activeIndex = idx
          applet.routeUrl = applet.route$Url + (query ? ((applet.route$Url.indexOf('?') >= 0 ? '&' : '?') + query) : '')
          commit('RELOAD_APPLET', applet)
          return true
        }
        return false
      })
      if (!applet) {
        const url = '/joys-rest/joys-master-data/applets/' + appletId
        http.get(url).then(resp => {
          applet = resp.data
          if (applet && applet.constructor === Object) {
            applet.route$Url = applet.routeUrl
            applet.routeUrl = applet.route$Url + (query ? ((applet.route$Url.indexOf('?') >= 0 ? '&' : '?') + query) : '')
            commit('OPEN_APPLET', applet)
            const path = findMenuItem(state.menu, appletId, [])
            commit('ADD_PATH', path)
            dispatch('openAppletLog')
          } else {
            console.error('No applet with id \'' + appletId + '\' found')
          }
        }).catch(err => {
          console.log('ERROR:' + err)
        })
      }

    },
    /**
     * 关闭应用
     * @param commit
     * @param idx
     */
    closeApplet({commit}, idx) {
      commit('CLOSE_APPLET', idx)
      commit('DEL_PATH', idx)
    },
    /**
     * 关闭所有显示的应用
     * @param commit
     */
    closeDisplayApplet({commit}) {
      commit('CLOSE_DISPLAY_APPLET')
    },
    /**
     * 打开应用日志
     * @param amount
     */
    openAppletLog(amount) {
      const url = '/joys-rest/joys-admin/log/saveLog'
      let logInfo = {operationContent: '打开了' +amount.state.openAppletName + '应用'}
      http.post(url, logInfo).then(resp => {
        // applet = resp.data
      }).catch(err => {
        console.log('ERROR:' + err)
      })
    }
  },
  getters: {},
  modules: {}
})

export default store
